<?php

include_once ("model/productModel.php");

include_once ("_include/common.php");

class productController {
	public $model;
	public $pagesize;
	public $currentpage;

	public function __construct() {
		if (!$_REQUEST["pagesize"]) {
			$_REQUEST["pagesize"] = 12;
		}
		if (!$_REQUEST["page"]) {
			$_REQUEST["page"] = 1;
		}
		$this -> pagesize = $_REQUEST["pagesize"];
		$this -> currentpage = $_REQUEST["page"];
		$this -> model = new productModel($this -> pagesize);
	}

	public function invoke() {
		if ($_REQUEST['Submit']) {

			switch ($_REQUEST['Submit']) {				
				case 'Search' :
					$this -> searchProduct();
					break;
			}
		} else {

			if ($_REQUEST["ProductID"]) {
				$this -> loadProduct();
			} else {
				if ($_REQUEST["Category"]) {
					$this -> loadProducts();
				} else {
					$this -> loadNewProducts();
				}
			}
		}
	}

	public function searchProduct() {
		$filter = "WHERE 1 ";

		if ($_REQUEST["Name"]) {
			$filter .= "&& Name like '%" . $_REQUEST["Name"] . "%'";
		}

		if ($_REQUEST["PriceFrom"]) {
			$filter .= "&& Price > '" . $_REQUEST["PriceFrom"] . "'";
		}

		if ($_REQUEST["PriceFromTo"]) {
			$filter .= "&& Price < '" . $_REQUEST["PriceTo"] . "'";
		}

		$products = $this -> model -> searchProduct($filter);
		$pagecount = $this -> model -> pagecount;
		$categories = $this -> model -> selectCategories();

		$PageLink = getPageLinks($pagecount);
		$MSS = '';

		include 'view/listProduct.php';
	}

	public function loadProducts() {
		$Category = $_REQUEST["Category"];
		$categories = $this -> model -> selectCategories();
		$products = $this -> model -> selectProductsByCategory($Category, $this -> currentpage);
		$pagecount = $this -> model -> pagecount;
		$PageLink = getPageLinks($pagecount);

		include "view/listProduct.php";
	}

	public function loadNewProducts() {
		$categories = $this -> model -> selectCategories();
		$products = $this -> model -> selectNewProducts($this -> currentpage);
		$pagecount = $this -> model -> pagecount;
		$PageLink = getPageLinks($pagecount);

		include "view/listProduct.php";
	}

	public function loadProduct() {
		$ProID = $_REQUEST["ProductID"];
		$model = new productModel(4);
		$product = $model -> selectProductDetail($ProID);
		$product = $product[0];
		$category = $product["Category"];
		$categories = $this -> model -> selectCategories();
		$products = $model -> selectProductsByCategory($Category, $this -> currentpage);
		include "view/productDetail.php";
	}

}
?>